"use strict";
var path = require('path');
var fs = require('fs');
var _ = require('lodash');

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var devConf = require('../config/dev')

var entries = _.reduce(_.toPairs(devConf.entries),function(all, each){
  all[each[0]] = each[1];
  return all;
},{})

var config = {
  entry: entries,
  output: {
    path: path.resolve(__dirname,`../`),
    publicPath: "/",
    filename: '[name].js'
  },
  module: {
    loaders: [
      {test: /\.json$/, loader: 'json'},
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /(node_modules|bower_components)/,
        query: {
          "presets": [
            "es2015",
            "stage-1",
            "react"
          ],
          "plugins": [
            "transform-decorators-legacy",
            "transform-class-properties",
            "transform-object-rest-spread",

            "transform-runtime",
            "syntax-async-functions",
            "transform-regenerator",
            "transform-object-assign"
          ],
          "env": {
            "development": {
              "presets": ["react-hmre"]
            }
          }
        }
      },
      {test: /\.less$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader")},
      {test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader")},
      {test: /\.scss$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader")},
      //other assets
      {test: /\.eot(\?\w+)?/, loader: 'url?limit=5000'}, // 'file' ?
      {test: /\.(woff|woff2)(\?\w+)?/, loader: 'url?limit=5000&mimetype=application/font-woff'},
      {test: /\.ttf(\?\w+)?/, loader: 'url?limit=5000&mimetype=application/octet-stream'},
      {test: /\.svg(\?\w+)?/, loader: 'url?limit=5000&mimetype=image/svg+xml'},
      {test: /\.(png|jpg|gif)$/, loader: 'url?limit=25000'}
    ],
  },
  resolve: {
    modulesDirectories: ['node_modules', 'bower_components'],
    extensions: ['', '.js', '.jsx'],
    alias: {
      "mobiscroll": path.resolve(__dirname, "../lib/js/mobiscroll.custom-3.0.0-beta6.min")
    }
  },
  plugins: [
    new webpack.NoErrorsPlugin(),
  ]
};

// merge webpack config options
function merge(target, source) {
  // base props
  target = Object.assign( {}, target, _.pick(source, ['devtool']) )

  target.entry = Object.assign({}, target.entry, source.entry)
  target.output = Object.assign({}, target.output, source.output)
  target.plugins = target.plugins.concat( source.plugins )

  return target
}

module.exports.makeConfig = function(newConfig,cwd) {
  return merge(_.cloneDeep(config), newConfig);
}

module.exports.config = config
